using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using Widgetsphere.Core.Util;

namespace Widgetsphere.AutoAggregate.Website.Objects
{
	public static class GeoFinder
	{
		private static XmlDocument _document = null;

		public static GeoCode GetLocation(string zipCode)
		{
			if (_document == null)
			{	
				_document = new XmlDocument();
				_document.Load(HttpContext.Current.Server.MapPath(@"\xml\zipcodes.xml"));
			}

			XmlNode node = _document.SelectSingleNode("//statelist/state/ziplist/zip[@name='" + zipCode + "']");
			GeoCode retval = null;
			if (node != null)
			{
				retval = new GeoCode(decimal.Parse(XmlHelper.GetAttribute(node, "latitude", "0")), decimal.Parse(XmlHelper.GetAttribute(node, "longitude", "0")));
			}
			return retval;
		}

		public static string GetZip(decimal latitude, decimal longitude)
		{
			if (_document == null)
			{
				_document = new XmlDocument();
				_document.Load(HttpContext.Current.Server.MapPath(@"\xml\zipcodes.xml"));
			}

			XmlNode node = _document.SelectSingleNode("//statelist/state/ziplist/zip[@latitude='" + latitude.ToString("#0.000000") + "']");
			if (node != null)
			{
				return XmlHelper.GetAttribute(node, "name", "");
			}
			return "";

		}

	}
}
